package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoService userInfoService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录了
        String token = request.getHeader("token");
        UserInfo user = userInfoService.getUserByToken(token);
        //没有登录的话，看他需要在什么地方执行拦截,不是所有地方都需要拦截，贴了注解的方法才需要拦截
        //判断里面的条件是
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod)handler;
            //获取方法上面的注解
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                //判断方法上是否有注解，如果有就拦截，让用户登录，没有就放行
                if(user == null){
                    response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                    return false;
                }
            }
        }

        return true;
    }


}
